<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
<meta name="google-site-verification" content="kYQuniuaRZuL9fq0DATfL7extAwcqWG6Ki286ZMcpak" />
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">
<!-- 网站关键字  -->
  <meta name="keywords" content="web前端,前端博客,vue,js，html,css,html5,css3,node,express,git,react">
<!-- 网站作者  -->
  <meta name="author" content="wxb">
  <meta http-equiv="Cache-Control" content="no-transform">
  <meta http-equiv="Cache-Control" content="no-siteapp">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"blogwxb.cn","root":"/","scheme":"Gemini","version":"7.7.1","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="先声明一个useReducer文件123456789101112131415161718import &amp;#123; createContext &amp;#125; from &quot;react&quot;;export const initData &#x3D; &amp;#123; count: 0 &amp;#125;;&#x2F;&#x2F;初始数据&#x2F;&#x2F; 派发事件export const reducer &#x3D; (state , action) &#x3D;&gt; &amp;#">
<meta property="og:type" content="article">
<meta property="og:title" content="React的Hooks中useContext和useReduce组合使用实现redux效果">
<meta property="og:url" content="https://blogwxb.cn/2020/07/04/React%E7%9A%84Hooks%E4%B8%ADuseContext%E5%92%8CuseReduce%E7%BB%84%E5%90%88%E4%BD%BF%E7%94%A8%E5%AE%9E%E7%8E%B0redux%E6%95%88%E6%9E%9C/index.html">
<meta property="og:site_name" content="会飞的猪的个人博客">
<meta property="og:description" content="先声明一个useReducer文件123456789101112131415161718import &amp;#123; createContext &amp;#125; from &quot;react&quot;;export const initData &#x3D; &amp;#123; count: 0 &amp;#125;;&#x2F;&#x2F;初始数据&#x2F;&#x2F; 派发事件export const reducer &#x3D; (state , action) &#x3D;&gt; &amp;#">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-07-04T02:00:57.000Z">
<meta property="article:modified_time" content="2020-07-04T02:02:46.685Z">
<meta property="article:author" content="wxb">
<meta property="article:tag" content="React">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://blogwxb.cn/2020/07/04/React%E7%9A%84Hooks%E4%B8%ADuseContext%E5%92%8CuseReduce%E7%BB%84%E5%90%88%E4%BD%BF%E7%94%A8%E5%AE%9E%E7%8E%B0redux%E6%95%88%E6%9E%9C/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>React的Hooks中useContext和useReduce组合使用实现redux效果 | 会飞的猪的个人博客</title>
  


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?3bc21ab780489193ab1c6a33159920cd";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">会飞的猪的个人博客</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="archive fa-fw"></i>归档</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://blogwxb.cn/2020/07/04/React%E7%9A%84Hooks%E4%B8%ADuseContext%E5%92%8CuseReduce%E7%BB%84%E5%90%88%E4%BD%BF%E7%94%A8%E5%AE%9E%E7%8E%B0redux%E6%95%88%E6%9E%9C/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="wxb">
      <meta itemprop="description" content="主要是分享自己在web前端的一些入的坑，脱的坑的经历，也会是分享一些node后端的知识。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="会飞的猪的个人博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          React的Hooks中useContext和useReduce组合使用实现redux效果
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2020-07-04 10:00:57 / 修改时间：10:02:46" itemprop="dateCreated datePublished" datetime="2020-07-04T10:00:57+08:00">2020-07-04</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E5%89%8D%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">前端</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="先声明一个useReducer文件"><a href="#先声明一个useReducer文件" class="headerlink" title="先声明一个useReducer文件"></a>先声明一个useReducer文件</h1><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; createContext &#125; <span class="keyword">from</span> <span class="string">"react"</span>;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> initData = &#123; <span class="attr">count</span>: <span class="number">0</span> &#125;;<span class="comment">//初始数据</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 派发事件</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> reducer = <span class="function">(<span class="params">state , action</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">switch</span> (action.type) &#123;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">"add"</span>:</span><br><span class="line">            <span class="keyword">return</span> &#123; ...state, <span class="attr">count</span>: state.count + <span class="number">1</span> &#125;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">"sub"</span>:</span><br><span class="line">            <span class="keyword">return</span> &#123; ...state, <span class="attr">count</span>: state.count - <span class="number">1</span> &#125;;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">"change"</span>:</span><br><span class="line">            <span class="keyword">return</span> &#123; ...state, <span class="attr">count</span>: action.changeCount &#125;;</span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">            <span class="keyword">return</span> state</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> ContextData = createContext(&#123;&#125;);</span><br></pre></td></tr></table></figure>
<a id="more"></a>
<h1 id="在App-js中引入"><a href="#在App-js中引入" class="headerlink" title="在App.js中引入"></a>在App.js中引入</h1><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; reducer, ContextData, initData &#125; <span class="keyword">from</span> <span class="string">"./useReducer"</span> <span class="comment">//引入useReducer文件</span></span><br><span class="line"><span class="keyword">import</span>  Children <span class="keyword">from</span> <span class="string">"./Children"</span> <span class="comment">//引入Children组件</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">App</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">&lt;!-- 获取是state和dispatch --&gt;</span><br><span class="line">  <span class="keyword">const</span> [state, dispatch] = useReducer(reducer, initData);</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">  &lt;!--ContextData.Provider包裹子元素，让子元素获取到useContext中的值--&gt;</span><br><span class="line">    &lt;ContextData.Provider value=&#123;&#123;</span><br><span class="line">      state,</span><br><span class="line">      dispatch <span class="comment">// 把 dispatch 也作为 context 的一部分共享下去，从而在嵌套组件中调用以实现更新顶层的 state</span></span><br><span class="line">    &#125;&#125;&gt;</span><br><span class="line">      &lt;div className=<span class="string">"app"</span>&gt;</span><br><span class="line">            &lt;Children /&gt;</span><br><span class="line">      &lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">    &lt;/</span>ContextData.Provider&gt;</span><br><span class="line"></span><br><span class="line">  );</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> App;</span><br></pre></td></tr></table></figure>
<h1 id="子组件Children中调用"><a href="#子组件Children中调用" class="headerlink" title="子组件Children中调用"></a>子组件Children中调用</h1><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">import React, &#123;useEffect, useContext &#125; from &quot;react&quot;;</span><br><span class="line">import &#123; ContextData &#125; from &quot;..&#x2F;..&#x2F;useReducer&quot;;</span><br><span class="line">const Children &#x3D; ()&#x3D;&gt;&#123;</span><br><span class="line">    &lt;!-- 获取到useContext中存的值 --&gt;</span><br><span class="line">    const &#123; state, dispatch &#125; &#x3D; useContext(ContextData);</span><br><span class="line">    useEffect(()&#x3D;&gt;&#123;</span><br><span class="line">        dispatch(&#123;type:&quot;add&quot;&#125;) &#x2F;&#x2F;派发事件</span><br><span class="line">        console.log(state)      &#x2F;&#x2F;获取祖先组件的useReducer的值</span><br><span class="line">        dispatch(&#123;type:&quot;change&quot;,changeCount:110&#125;) &#x2F;&#x2F;派发事件，通过第二个参数去修改值</span><br><span class="line">    &#125;,[])</span><br><span class="line">  return(</span><br><span class="line">    &lt;div&gt;</span><br><span class="line">        children子组件</span><br><span class="line">    &lt;&#x2F;div&gt;</span><br><span class="line">  )</span><br><span class="line">&#125;</span><br><span class="line">export default Children;</span><br></pre></td></tr></table></figure>

    </div>

    
    
    
        <div class="reward-container">
  <div></div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/wechatpay.png" alt="wxb 微信支付">
        <p>微信支付</p>
      </div>
      
      <div style="display: inline-block;">
        <img src="/images/alipay.png" alt="wxb 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/React/" rel="tag"># React</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/06/19/Node%E5%A6%82%E4%BD%95%E8%8E%B7%E5%8F%96%E5%89%8D%E7%AB%AF%E7%9A%84cookie/" rel="prev" title="Node如何获取前端的cookie">
      <i class="fa fa-chevron-left"></i> Node如何获取前端的cookie
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/07/05/Express%E4%B8%AD%E7%9A%84socket-io/" rel="next" title="Express中的socket.io">
      Express中的socket.io <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#先声明一个useReducer文件"><span class="nav-number">1.</span> <span class="nav-text">先声明一个useReducer文件</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#在App-js中引入"><span class="nav-number">2.</span> <span class="nav-text">在App.js中引入</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#子组件Children中调用"><span class="nav-number">3.</span> <span class="nav-text">子组件Children中调用</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="wxb"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">wxb</p>
  <div class="site-description" itemprop="description">主要是分享自己在web前端的一些入的坑，脱的坑的经历，也会是分享一些node后端的知识。</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">27</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">2</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">10</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/dearDreamWeb" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;dearDreamWeb" rel="noopener" target="_blank"><i class="github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://gitee.com/flyingwxb" title="Gitee → https:&#x2F;&#x2F;gitee.com&#x2F;flyingwxb" rel="noopener" target="_blank"><i class="gitee fa-fw"></i>Gitee</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">wxb</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div><script color="0,0,0" opacity="0.5" zIndex="-1" count="99" src="https://cdn.jsdelivr.net/npm/canvas-nest.js@1/dist/canvas-nest.js"></script>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>















  

  

</body>
</html>
